package main

import (
	"github.com/sirupsen/logrus"
	"os"
	"os/signal"
	"syscall"
	"watcher/client"
	"watcher/client/config"
	"watcher/client/watcher"
)

var watcherMap = map[string]watcher.WatcherRegister{
	"cpu":     watcher.CpuRegister,
	"memory":  watcher.MemoryRegister,
	"redis":   watcher.RedisRegister,
	"disk":    watcher.DiskRegister,
	"loadavg": watcher.LoadavgRegister,
	"io":      watcher.IORegister,
}

func main() {
	//日志配置
	level, err := logrus.ParseLevel(config.Config.Level)
	if err != nil {
		logrus.Fatalf("unsupported log level %s!", config.Config.Level)
	}
	logrus.StandardLogger().SetLevel(level)

	c := client.NewClient(config.Config)
	c.RegisterWatcher(parseWatchers(config.Config.Watchers)...)
	c.Listen()
	c.Report()
	s := make(chan os.Signal)
	signal.Notify(s, syscall.SIGQUIT, syscall.SIGSTOP, syscall.SIGINT)
	select {
	case sign := <-s:
		logrus.Infof("收到信号[%d]，关闭客户端", sign)
		c.Close()
	}
}

func parseWatchers(wts []string) []watcher.WatcherRegister {
	var wRegisters []watcher.WatcherRegister
	for _, w := range wts {
		wr, ok := watcherMap[w]
		if ok {
			wRegisters = append(wRegisters, wr)
		} else {
			logrus.Warnf("未知的监听器[%s]", w)
		}
	}
	return wRegisters
}
